package com.jiexin.service;

import com.google.common.base.Preconditions;
import com.jiexin.beans.PageResult;
import com.jiexin.common.RequestHolder;
import com.jiexin.dao.SysRoleMapper;
import com.jiexin.exception.ParamException;
import com.jiexin.model.SysRole;
import com.jiexin.param.RoleParam;
import com.jiexin.util.BeanValidator;
import com.jiexin.util.IpUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @Author: Jay_Liu
 * @Description:
 * @Date: Created in 16:23 2018/4/20 0020
 * @Modified By:
 */
@Service
public class SysRoleService {

    @Resource
    SysRoleMapper sysRoleMapper;

    @Resource
    private SysLogService sysLogService;

    public void save(RoleParam param) {
        BeanValidator.check(param);
        if(checkIsExist(param.getName(), param.getId())) {
            throw new ParamException("不允许存在相同角色名称");
        }
        SysRole role = SysRole.builder().name(param.getName()).type(param.getType()).status(param.getStatus())
                .remark(param.getRemark()).build();
        role.setOperator(RequestHolder.getCurrentUser().getUsername());
        role.setOperateTime(new Date());
        role.setOperateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest()));
        sysRoleMapper.insertSelective(role);
        sysLogService.saveRoleLog(null, role);
    }

    public void update(RoleParam param) {
        BeanValidator.check(param);
        if(checkIsExist(param.getName(), param.getId())) {
            throw new ParamException("不允许存在相同角色名称");
        }
        SysRole before = sysRoleMapper.selectByPrimaryKey(param.getId());
        Preconditions.checkNotNull(before,"待更新的角色不存在");
        //日志记录原先的角色信息 TODO：
        //新的角色信息
        SysRole after = SysRole.builder().id(param.getId()).name(param.getName()).type(param.getType()).status(param.getStatus())
                .remark(param.getRemark()).build();
        after.setOperator(RequestHolder.getCurrentUser().getUsername());
        after.setOperateTime(new Date());
        after.setOperateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest()));
        sysRoleMapper.updateByPrimaryKeySelective(after);
        sysLogService.saveRoleLog(before, after);
    }

    public List<SysRole> getAllRole() {
        return sysRoleMapper.getAllRole();
    }

    /**
     * 检查是否存在相同名称的角色
     * @param name 角色名称
     * @param id 角色ID
     * @return 布尔
     */
    private boolean checkIsExist(String name, Integer id) {
        return sysRoleMapper.countByNameAndRoleId(name, id) > 0;
    }


}
